<template>
  <div class="main-todo">
    <input type="text" placeholder="what do want to do?" class="add-todo" autofocus v-model="content"
      @keyup.enter="add" />
    <todo-item v-for="(item,index) of filterState" :key="index+1" :todo="item" @del="handleDelItem"></todo-item>
    <todo-info :total="total" @handleState="handleStateFa" @clearCompleted="clCompleted"></todo-info>
  </div>
</template>

<script>
import todoItem from './comps/todoItem.vue'
import todoInfo from './comps/todoInfo.vue'

let id = 0
export default {
  name: 'mainTodo',
  data () {
    return { todoData: [], content: '', total: 0, state: 'all' }
  },
  components: { todoItem, todoInfo },
  watch: {
    todoData: {
      deep: true,
      handler (n, o) {
        this.total = this.todoData.filter(
          item => item.completed == false
        ).length
      }
    }
  },

  computed: {
    filterState () {
      switch (this.state) {
        case 'all':
          return this.todoData
        case 'actived':
          return this.todoData.filter(item => item.completed == false)
        case 'completed':
          return this.todoData.filter(item => item.completed == true)
      }
    }
  },
  methods: {
    add () {
      if (this.content === '') return
      id++
      this.todoData.unshift({
        id: id,
        content: this.content,
        completed: false
      })
      this.content = ''
    },
    handleDelItem (id) {
      this.todoData.splice(
        this.todoData.findIndex(item => item.id === id),
        1
      )
    },
    handleStateFa (state) {
      this.state = state
    },
    clCompleted () {
      this.todoData = this.todoData.filter(item => item.completed == false)
    }
  }
}
</script>
<style lang="stylus" scoped>
.main-todo {
  width: 600px;
  margin: 0 auto;
  background-color: #fff;
  box-shadow: 0 0 5px #666666;

  .add-todo {
    font-size: 24px;
    font-weight: inherit;
    font-family: inherit;
    color: inherit;
    border: none;
    outline: none;
    padding: 16px 16px 16px 36px;
    box-sizing: border-box;
    width: 100%;
  }
}
</style>
